package com.auxgroup.smarthome.web.listener;

import com.auxgroup.smarthome.IserverInitService;
import com.auxgroup.smarthome.basebean.MenuTypeEnum;
import com.auxgroup.smarthome.entity.MenuEntity;
import com.auxgroup.smarthome.entity.RoleEntity;
import com.auxgroup.smarthome.entity.RoleTag;
import com.auxgroup.smarthome.entity.UserEntity;
import com.auxgroup.smarthome.filter.annotation.PermissionMenu;
import com.auxgroup.smarthome.repo.MenuRepo;
import com.auxgroup.smarthome.repo.RoleRepo;
import com.auxgroup.smarthome.repo.UserRepo;
import com.auxgroup.smarthome.utils.EncryptionUtils;
import com.auxgroup.smarthome.web.filter.PermissionUpmsMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

@Service
public class SystemInitListener implements IserverInitService {

    @Value("${server.contextPath}")
    protected String contextPath;

    @Autowired
    private PermissionUpmsMenu permissionUpmsMenu;

    @Autowired
    private MenuRepo menuRepository;
    @Autowired
    private RoleRepo roleRepository;
    @Autowired
    private UserRepo userRepository;

    private ConfigurableApplicationContext applicationContext;


    @Override
    public void appStartedOperate(ApplicationEvent event) {
        this.applicationContext = ((ApplicationReadyEvent) event).getApplicationContext();
        permissionUpmsMenu.buildMenus();
        initPermissionData();
        initRoleAndUser();
    }

    private void initPermissionData() {
        List<Object[]> list = permissionUpmsMenu.buildMenus();
        List<MenuEntity> menuEntities = new ArrayList<>();
        list.stream().forEach(objects -> {
            String url = objects[0].toString();
            PermissionMenu permissionMenu = (PermissionMenu) objects[1];
            String id = permissionMenu.id(),
                    menuName = permissionMenu.name(),
                    parentId = null == permissionMenu.parentId() || "".equals(permissionMenu.parentId()) ? null : permissionMenu.parentId();
            MenuTypeEnum menuType = permissionMenu.menuType();
            MenuEntity menuEntity = menuRepository.findOne(id);
            if(null == menuEntity) {
                menuEntity = new MenuEntity(id, menuName, parentId, menuType, url);
            }
            menuEntities.add(menuEntity);
        });
        menuRepository.save(menuEntities);
    }

    /**
     * 初始化角色数据 与 系统超级用户
     */
    private void initRoleAndUser() {
        List<MenuEntity> menuEntities = menuRepository.findAll();
        RoleEntity supperRole = roleRepository.findByRoleTag(RoleTag.SUPPERROLE);
        if (supperRole == null) {
            supperRole = new RoleEntity("超级管理员", "由系统自动创建，拥有该系统所有操作权限", RoleTag.SUPPERROLE);
        }
        supperRole.setMenus(new HashSet<MenuEntity>(menuEntities));
        roleRepository.save(supperRole);
        UserEntity adminUser = userRepository.findByUserName("admin");
        if (adminUser == null) {
            adminUser = new UserEntity("admin", "奥克斯",  "13000000000", supperRole);
            String salt = UUID.randomUUID().toString();
            String pwd = EncryptionUtils.md5("12345678" + salt);
            adminUser.setPassword(pwd);
            adminUser.setSalt(salt);
            userRepository.save(adminUser);
        }
    }

    @Override
    public void appClosedOperate(ApplicationEvent event) {
        System.err.println("demo: 此进程关闭后，清除此进程中所有缓存！！！");
    }


}
